package com.mall.security;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.mall.common.entity.PowerInfo;
import com.mall.common.entity.ShiroUser;
import com.mall.common.token.UserAuthenticationToken;

/**
 * shiro权限过滤
 * @author tgy
 *
 */
public class UserRealm extends AuthorizingRealm{
	
	/**
	 * 认证，身份认证/登录，验证用户是不是拥有相应的身份
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		try{
			
			UserAuthenticationToken auth = (UserAuthenticationToken) token;
			if(auth!=null){
				if(auth.getPower()!=null&&auth.getPower().size()>0){
					return new SimpleAuthenticationInfo(new ShiroUser(auth.getId(), auth.getUsername(), auth.getPower()),auth.getPassword(),getName());
				}
			}
		}catch(Exception e){
		}
		return null;
	}
	
	/**
	 * 授权，即权限验证，验证某个已认证的用户是否拥有某个权限；即判断用户是否能做事情
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
		SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
		ShiroUser user = (ShiroUser) collection.getPrimaryPrincipal();
		if(user != null && user.getPower() != null && !user.getPower().isEmpty()) {
			Set<String> roles = new HashSet<String>();
			for(PowerInfo pi:user.getPower()){
				roles.add(pi.getName());
			}
			user.setRoles(roles);
			auth.addStringPermissions(roles);
		}
		return auth;
	}
}
